package id.mankel.commons.i18n;

import id.mankel.commons.ApplicationContextHolder;
import org.springframework.context.MessageSource;

import java.util.Arrays;

/**
 * @author Mankel
 */
public interface I18nEnum {

    /**
     * Returns the value of the enum.
     *
     * @return value of the enum
     */
    Object getValue();

    /**
     * Returns the i18n key of the enum.
     *
     * @return i18n key of the enum
     */
    String getI18nKey();

    /**
     * Returns the i18n name of the enum by value.
     *
     * @param eClass enum class
     * @param value enum value
     * @return i18n name of the enum by value
     */
    default <E> String getI18nName(Class<E> eClass, Object value) {
        if (!eClass.isEnum()) {
            return null;
        }
        if (Arrays.stream(eClass.getInterfaces()).noneMatch(I18nEnum.class::equals)) {
            return null;
        }
        if (null == value) {
            return null;
        }
        I18nEnum[] es = (I18nEnum[]) eClass.getEnumConstants();
        I18nEnum t = Arrays.stream(es).filter(e -> e.getValue().equals(value)).findFirst().orElse(null);
        if (null == t) {
            return null;
        }
        // TODO locale?
        return ApplicationContextHolder.getBean(MessageSource.class).getMessage(t.getI18nKey(), null, null);
    }

}
